//
//  InviteFriendsViewController.m
//  安好
//
//  Created by lianchuang on 14-8-26.
//  Copyright (c) 2014年 冯凯. All rights reserved.
//

#import "InviteFriendsViewController.h"
#import "InviteFriendViewCell.h"
#import "ObtainQualificationsViewController.h"
#import <TencentOpenAPI/TencentOAuth.h>
#import "TencentOpenAPI/QQApiInterface.h"
#import <TencentOpenAPI/TencentApiInterface.h>
#import "WXApi.h"
#import "MainViewController.h"
#import "AppDelegate.h"
@interface InviteFriendsViewController ()
@end

@implementation InviteFriendsViewController
{
    NSArray *titleNames;
    NSArray *Images;
    NSMutableDictionary *statusDic;
    NSInteger weChatCount;
    NSInteger QQCount;
    CGFloat value;
    BOOL isWXChatTimeline;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}
- (void)viewWillDisappear:(BOOL)animated
{
}
- (void)viewWillAppear:(BOOL)animated
{
    if (weChatCount>=QQCount) {
        value=weChatCount*0.04;
    }else
    {
        value=QQCount*0.04;
    }
    if ([[[NSUserDefaults standardUserDefaults]valueForKey:@"sina"] isEqualToString:@"1"]) {
        value=1.0;
    }
    if ([[[NSUserDefaults standardUserDefaults]valueForKey:@"wechatCircle"] isEqualToString:@"1"]) {
        value=1.0;
    }
    [self resetValue];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doChange:) name:@"WeChat" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doChangeSina:) name:@"Sina" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doChangeQQ:) name:@"QQ" object:nil];
}
/**
 *  重新部署slider的值
 */
- (void)resetValue
{
    if (value<=0.0) {
        self.slider.value=0.8;
        self.sliderLabel.frame=CGRectMake((kScreenWidth-50)/5*4+4,self.slider.top-37, 43, 21);
        self.sliderBub.frame=CGRectMake((kScreenWidth-50)/5*4+4,self.slider.top-38, 43, 32);
        self.sliderLabel.text=@"80%";
        self.finishSender.userInteractionEnabled=NO;
    }else if (value>0&&value<=0.04){
        self.slider.value=0.84;
        self.sliderLabel.frame=CGRectMake((kScreenWidth-50)/5*4+(kScreenWidth-50)/5/5+4,self.slider.top-37, 43, 21);
        self.sliderBub.frame=CGRectMake((kScreenWidth-50)/5*4+(kScreenWidth-50)/5/5+4,self.slider.top-38, 43, 32);
        self.sliderLabel.text=@"84%";
        self.finishSender.userInteractionEnabled=NO;
    }else if (value>0.04&&value<=0.08){
        self.slider.value=0.88;
        self.sliderLabel.frame=CGRectMake((kScreenWidth-50)/5*4+(kScreenWidth-50)/5/5*2+4,self.slider.top-37, 43, 21);
        self.sliderBub.frame=CGRectMake((kScreenWidth-50)/5*4+(kScreenWidth-50)/5/5*2+4,self.slider.top-38, 43, 32);
        self.sliderLabel.text=@"88%";
        self.finishSender.userInteractionEnabled=NO;
    }else if (value>0.08&&value<=0.12){
        self.slider.value=0.92;
        self.sliderLabel.frame=CGRectMake((kScreenWidth-50)/5*4+(kScreenWidth-50)/5/5*3+4,self.slider.top-37, 43, 21);
        self.sliderBub.frame=CGRectMake((kScreenWidth-50)/5*4+(kScreenWidth-50)/5/5*3+4,self.slider.top-38, 43, 32);
        self.sliderLabel.text=@"92%";
        self.finishSender.userInteractionEnabled=NO;
    }else if (value>0.12&&value<=0.16){
        self.slider.value=0.96;
        self.sliderLabel.frame=CGRectMake((kScreenWidth-50)/5*4+(kScreenWidth-50)/5/5*4+4,self.slider.top-37, 43, 21);
        self.sliderBub.frame=CGRectMake((kScreenWidth-50)/5*4+(kScreenWidth-50)/5/5*4+4,self.slider.top-38, 43, 32);
        self.sliderLabel.text=@"96%";
        self.finishSender.userInteractionEnabled=NO;
    }else if (value>0.16&&value<=0.2){
        self.slider.value=1.0;
        self.sliderLabel.frame=CGRectMake(kScreenWidth-50+4,self.slider.top-37, 43, 21);
        self.sliderBub.frame=CGRectMake(kScreenWidth-50+4,self.slider.top-38, 43, 32);
        self.sliderLabel.text=@"100%";
        self.finishSender.userInteractionEnabled=YES;
        [self.finishSender setBackgroundImage:[UIImage imageNamed:@"finish.png"] forState:UIControlStateNormal];
        [self.slider setThumbImage:[UIImage imageNamed:@"slider_center1.png"] forState:UIControlStateNormal];
    }else
    {
        self.slider.value=1.0;
        self.sliderLabel.frame=CGRectMake(kScreenWidth-50+4,self.slider.top-37, 43, 21);
        self.sliderBub.frame=CGRectMake(kScreenWidth-50+4,self.slider.top-38, 43, 32);
        self.sliderLabel.text=@"100%";
        self.finishSender.userInteractionEnabled=YES;
        [self.finishSender setBackgroundImage:[UIImage imageNamed:@"finish.png"] forState:UIControlStateNormal];
        [self.slider setThumbImage:[UIImage imageNamed:@"slider_center1.png"] forState:UIControlStateNormal];
    }
}
/**
 *  创建返回按钮
 */
-(void)makeNavBar{
    self.navigationItem.title = @"设置";
    UIBarButtonItem *backBtnImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(backBtnclicked)];
    backBtnImg.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = backBtnImg;
}
/**
 *  返回
 */
- (void)backBtnclicked
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewDidLoad
{

    [super viewDidLoad];
    self.navigationItem.title=@"邀请好友";
    self.view.backgroundColor=[ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
    [self makeNavBar];
    if ([[NSUserDefaults standardUserDefaults] valueForKey:@"wechatcount"]) {
        weChatCount=[[[NSUserDefaults standardUserDefaults] valueForKey:@"wechatcount"] integerValue];
    }else{
        weChatCount=0;
    }
    if ([[NSUserDefaults standardUserDefaults] valueForKey:@"qqcount"]) {
        QQCount=[[[NSUserDefaults standardUserDefaults] valueForKey:@"qqcount"] integerValue];
    }else{
        QQCount=0;
    }
    self.slider=[[UISlider alloc]init];
    
    self.sliderBG.frame=CGRectMake(0, 15, kScreenWidth, 60);
    self.slider.frame=CGRectMake(25, 62, kScreenWidth-50, 2);
    
    NSUserDefaults *userDefult=[NSUserDefaults standardUserDefaults];
    if ([[userDefult objectForKey:@"archives"] isEqualToString:@"1"]&&[[userDefult valueForKey:@"invite"] isEqualToString:@"1"]) {
        [self successInvite];
        self.finishSender.userInteractionEnabled=YES;
        [self.finishSender setBackgroundImage:[UIImage imageNamed:@"finish.png"] forState:UIControlStateNormal];

    }else
    {
        self.slider.value=0.8;
        self.sliderLabel.frame=CGRectMake((kScreenWidth-50)/5*4+4,self.slider.top-37, 43, 21);
        self.sliderBub.frame=CGRectMake((kScreenWidth-50)/5*4+4,self.slider.top-38, 43, 32);
        self.sliderLabel.text=@"80%";
        self.finishSender.userInteractionEnabled=NO;
    }

    self.tableview.frame=CGRectMake(0, self.sliderBG.bottom, kScreenWidth,kScreenWidth==414?270: 230);
    
    self.tableview.delegate=self;
    self.tableview.dataSource=self;
//    self.view.backgroundColor=[self colorWithHexString:@"#ecf4f6"];
//    self.tableview.backgroundColor=[self colorWithHexString:@"#ecf4f6"];
    
    [self.view addSubview:self.tableview];
    self.slider.backgroundColor = [UIColor clearColor];

    self.slider.userInteractionEnabled=NO;
    self.slider.minimumValue=0.0;
    self.slider.maximumValue=1.0;
    [self.slider setMinimumTrackImage:[UIImage imageNamed:@"slider_left.png"] forState:UIControlStateNormal];
    [self.slider setMaximumTrackImage:[UIImage imageNamed:@"slider_right.png"] forState:UIControlStateNormal];
    [self.slider setThumbImage:[UIImage imageNamed:@"slider_center.png"] forState:UIControlStateNormal];
    [self.view addSubview:self.slider];
    self.tableview.separatorStyle=UITableViewCellSeparatorStyleNone;
    
    titleNames=@[@"发送1条微信朋友圈动态",@"邀请5个微信好友",@"邀请5个QQ好友",@"发送1条微博动态"];
    Images=@[@"invite_ friendCircle.png",@"invite_weChat.png",@"invite_QQ.png",@"invite_sina.png"];
    statusDic=[[NSMutableDictionary alloc]initWithObjectsAndKeys:@"",@"Circle",@"",@"Chat",@"",@"QQ",@"",@"sina", nil];
    

    if (QQCount>0) {
        [statusDic setValue:[NSString stringWithFormat:@"%ld个",QQCount] forKey:@"QQ"];
    }
    if (weChatCount>0) {
        [statusDic setValue:[NSString stringWithFormat:@"%ld个",weChatCount] forKey:@"Chat"];
    }
    
    if ([[[NSUserDefaults standardUserDefaults]valueForKey:@"sina"] isEqualToString:@"1"]){
        [statusDic setValue:@"已完成" forKey:@"sina"];
    }
    if ([[[NSUserDefaults standardUserDefaults]valueForKey:@"wechatCircle"] isEqualToString:@"1"]) {
        [statusDic setValue:@"已完成" forKey:@"Circle"];
    }
    [self.tableview reloadData];
    self.finishSender.frame=CGRectMake(15,kScreenHeight-46-15-64, kScreenWidth-30, IPhone6Plus?56 :46);
    self.backInvView.frame = CGRectMake(0, kScreenHeight-50-64, kScreenWidth, 64);
    [self.finishSender setBackgroundImage:[UIImage imageNamed:@"obtain_unfinish.png"] forState:UIControlStateNormal];
    
    
}
/**
 *  qq分享成功后
 *
 *  @param not 通知内容
 */
- (void)doChangeQQ:(NSNotification *)not
{
    QQCount++;
    [statusDic setValue:[NSString stringWithFormat:@"%ld个",QQCount] forKey:@"QQ"];
    [[NSUserDefaults standardUserDefaults]setValue:[NSString stringWithFormat:@"%ld",QQCount] forKey:@"qqcount"];
    if (weChatCount>=QQCount) {
        if (value>=weChatCount*0.04) {
        }
        else  value=weChatCount*0.04;

    }else
    {
        if (value>=QQCount*0.04) {
        }
        else  value=QQCount*0.04;
    }
    [self resetValue];
    if (QQCount>=5) {
        [statusDic setValue:@"已完成" forKey:@"QQ"];
        self.finishSender.userInteractionEnabled=YES;
        [self.finishSender setBackgroundImage:[UIImage imageNamed:@"finish.png"] forState:UIControlStateNormal];
        [self successInvite];
        QQCount=5;
    }
    [self.tableview reloadData];
}
/**
 *  新浪分享成功
 *
 *  @param not 通知的内容
 */
- (void)doChangeSina:(NSNotification *)not
{
    [statusDic setValue:@"已完成" forKey:@"sina"];
    self.finishSender.userInteractionEnabled=YES;
    [self.finishSender setBackgroundImage:[UIImage imageNamed:@"finish.png"] forState:UIControlStateNormal];
    [[NSUserDefaults standardUserDefaults]setValue:@"1" forKey:@"sina"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [self successInvite];
    self.view.frame=CGRectMake(self.view.frame.origin.x , self.view.frame.origin.y, kScreenWidth, kScreenHeight);
    [self.tableview reloadData];

}
/**
 *  微信分享
 *
 *  @param not 分享内容
 */
- (void)doChange:(NSNotification *)not
{
    MyNSLog("%@",[not.userInfo valueForKey:@"type"]);
    if([[not.userInfo valueForKey:@"type"] isKindOfClass:[SendMessageToWXResp class]]){
        SendMessageToWXResp *resp=[not.userInfo valueForKey:@"type"];
        if (resp.errCode==0) {
            MyNSLog("分享成功！");
            if (!isWXChatTimeline) {
                weChatCount++;
                [statusDic setValue:[NSString stringWithFormat:@"%ld个",weChatCount] forKey:@"Chat"];
                [[NSUserDefaults standardUserDefaults]setValue:[NSString stringWithFormat:@"%ld",weChatCount] forKey:@"wechatcount"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                if (weChatCount>=QQCount) {
                    if (value<= weChatCount*0.04) {
                        value=weChatCount*0.04;
                    }
                }else
                {
                    if (value<=QQCount*0.04) {
                        value=QQCount*0.04;
                    }
                }
                [self resetValue];
                if (weChatCount>=5) {
                    [statusDic setValue:@"已完成" forKey:@"Chat"];
                    self.finishSender.userInteractionEnabled=YES;
                    [self.finishSender setBackgroundImage:[UIImage imageNamed:@"finish.png"] forState:UIControlStateNormal];
                    [self successInvite];
                    weChatCount=5;
                }
            }else
            {
                [statusDic setValue:@"已完成" forKey:@"Circle"];
                self.finishSender.userInteractionEnabled=YES;
                [self.finishSender setBackgroundImage:[UIImage imageNamed:@"finish.png"] forState:UIControlStateNormal];
                [[NSUserDefaults standardUserDefaults]setValue:@"1" forKey:@"wechatCircle"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                [self successInvite];

            }
            [self.tableview reloadData];

        }
    }else if ([[not.userInfo valueForKey:@"type"] isKindOfClass:[SendMessageToWXReq class]])
    {
        MyNSLog("分享成功！");
        [statusDic setValue:@"已完成" forKey:@"Circle"];
        self.finishSender.userInteractionEnabled=YES;
        [self.finishSender setBackgroundImage:[UIImage imageNamed:@"finish.png"] forState:UIControlStateNormal];
        [self successInvite];
        [self.tableview reloadData];
 
    }
}
#pragma  mark UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section==0) {
        UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 40)];
//        view.backgroundColor=[self colorWithHexString:@"#ecf4f6"];
        
        UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(15, 10, 200, 20)];
        label.font=[UIFont systemFontOfSize:LABEL_FONT_SIZE_TITLE];
        label.text=@"操作任一项即可完成任务";
        label.backgroundColor=[UIColor clearColor];
        [view addSubview:label];
        view.backgroundColor=[ClassMethodsViewController colorWithHexString:@"#EBEBEB"];
        return view;
    }else
    {
        UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 10)];
        view.backgroundColor=[ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
        return view;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *indentifier=@"cell";
    InviteFriendViewCell *cell=[tableView dequeueReusableCellWithIdentifier:indentifier];
    if (cell==nil) {
        if (kScreenWidth==414) {
            cell=[[[NSBundle mainBundle]loadNibNamed:@"InviteFriendViewCell" owner:self options:nil] lastObject];
        }else
        {
            cell=[[[NSBundle mainBundle]loadNibNamed:@"InviteFriendViewCell" owner:self options:nil] firstObject];
        }
    }
    cell.itemImageview.image=[UIImage imageNamed:[Images objectAtIndex:indexPath.section]];
    cell.itemName.text=[titleNames objectAtIndex:indexPath.section];
    if (indexPath.section==0) {
        cell.itemStatus.text=[statusDic valueForKey:@"Circle"];
    }else if (indexPath.section==1)
    {
        cell.itemStatus.text=[statusDic valueForKey:@"Chat"];
    }
    else if (indexPath.section==2)
    {
        cell.itemStatus.text=[statusDic valueForKey:@"QQ"];
    }
    else{
        cell.itemStatus.text=[statusDic valueForKey:@"sina"];
    }
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (kScreenWidth==414) {
        return 50;
    }
    return 40;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section==0) {
        return 40;
    }else return 10;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSString *title = @"安好客户端";
    NSString *descriptions = @"我正在使用安好客户端，在这里可以跟网友聊聊健康，如有身体不适还可以自我诊断，甚至可以挂号，强大的医院库，医生库，坐在家里就可以跟医生面对面的进行咨询。";
    UIImage *image=[UIImage imageNamed:@"Icon.png"];
    NSString *webpageUrl=@"http://www.niruoanhao.com/autodownload/";

    //直接分享到微信朋友圈，微信好友，qq，新浪
    if (indexPath.section==0) {
        isWXChatTimeline=YES;
        [self weixinFriendShare:webpageUrl :title :descriptions :image]; 
    }else if (indexPath.section==1){
        isWXChatTimeline=NO;
        [self weixinShare:webpageUrl :title :descriptions :image];
    }else if (indexPath.section==2){
        [self qqShare:webpageUrl :title :descriptions :image];

    }else{
        [self sinaWeiboShare :webpageUrl :title :descriptions :image];
    }
}
/**
 *  任务完成时，设置slider状态
 */
- (void)successInvite
{
    self.slider.value=1.0;
    self.sliderLabel.frame=CGRectMake((kScreenWidth-50)+4,self.slider.top-37, 43, 21);
    self.sliderBub.frame=CGRectMake((kScreenWidth-50)+4,self.slider.top-38, 43, 32);
    self.sliderLabel.text=@"100%";
    [self.slider setThumbImage:[UIImage imageNamed:@"slider_center1.png"] forState:UIControlStateNormal];

}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
/**
 *  完成按钮，提交服务器状态
 *
 *  @param sender button
 */
- (IBAction)doFinshClick:(UIButton *)sender {
    
    [self showActionView];
    NSString * postURL = [NSString stringWithFormat:@"%@user/invite/",kBaseURL];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSDictionary *parameters = @{
                                 @"platform": kPlatform,
                                 @"version":kVersion,
                                 @"isinvite":@"1",
                                 };
    [manager POST:postURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self hiddenActionView];
        if ([[responseObject valueForKey:@"msg"] isEqualToString:@"更新成功"]) {
            NSUserDefaults *userDefult=[NSUserDefaults standardUserDefaults];
            [userDefult setValue:@"1" forKey:@"invite"];
            ObtainQualificationsViewController *obtain=[[[[(MainViewController*)self.tabBarController viewControllers] objectAtIndex:1] viewControllers] objectAtIndex:1];
            if (self.delegate&&[self.delegate respondsToSelector:@selector(finishInvite)]) {
                [self.delegate finishInvite];
            }
            /**
             *  移除通知
             */
            [[NSNotificationCenter defaultCenter] removeObserver:self name:@"WeChat" object:nil];
            [[NSNotificationCenter defaultCenter] removeObserver:self name:@"Sina" object:nil];
            [[NSNotificationCenter defaultCenter] removeObserver:self name:@"QQ" object:nil];
            [self.navigationController popToViewController:obtain animated:YES];
        }
        else if([[responseObject valueForKey:@"msg"] isEqualToString:@"更新失败"])
        {
            ObtainQualificationsViewController *obtain=[[[[(MainViewController*)self.tabBarController viewControllers] objectAtIndex:1] viewControllers] objectAtIndex:1];
            if (self.delegate&&[self.delegate respondsToSelector:@selector(finishInvite)]) {
                [self.delegate finishInvite];
            }
            [self.navigationController popToViewController:obtain animated:YES];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self hiddenActionView];
    }];

    
    
}
@end
